﻿using Nancy;
using Nancy.ModelBinding;
using Nancy.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace TaskManagementSystem.Modules.Home
{
    public class HomeModule : FrontModule
    {
        public HomeModule()
        {
            Get["/"] = _ =>
            {
                Data.DbContext dbContext = Data.DbContext.CurrentContext;
                List<Entity.SystemCronConfigData> list = dbContext.SystemCronConfigData.OrderBy(x => x.AddTime).ToList();
                return View["Home/Index", list];
            };

            Post["/run"] = _ =>
            {
                int jobid = int.Parse(Request.Query.id);
                Data.DbContext dbContext = Data.DbContext.CurrentContext;
                Entity.SystemCronConfigData data = dbContext.SystemCronConfigData.Where(x => x.JobId == jobid).FirstOrDefault();
                data.IsValidity = true;
                dbContext.Entry(data).State = System.Data.Entity.EntityState.Modified;
                dbContext.SaveChanges();
                ScheduledTask.ScheduledTaskManager.ExecuteTask(data);
                return new Models.CommandResult();
            };


            Post["/run_all"] = _ =>
            {
                Task task = Task.Factory.StartNew(() =>
                {
                    Thread.CurrentThread.IsBackground = false;
                    Data.DbContext dbContext = Data.DbContext.CurrentContext;
                    List<Entity.SystemCronConfigData> list = dbContext.SystemCronConfigData.ToList();

                    list.ForEach(data =>
                    {
                        data.IsValidity = true;
                        dbContext.Entry(data).State = System.Data.Entity.EntityState.Modified;
                        ScheduledTask.ScheduledTaskManager.ExecuteTask(data);
                    });
                    dbContext.SaveChanges();
                });
                return new Models.CommandResult();
            };

            Post["/stop"] = _ =>
            {
                int jobid = int.Parse(Request.Query.id);
                Data.DbContext dbContext = Data.DbContext.CurrentContext;
                Entity.SystemCronConfigData data = dbContext.SystemCronConfigData.Where(x => x.JobId == jobid).FirstOrDefault();
                data.IsValidity = false;
                dbContext.Entry(data).State = System.Data.Entity.EntityState.Modified;
                dbContext.SaveChanges();
                ScheduledTask.ScheduledTaskManager.StopTask(data);
                return new Models.CommandResult();
            };

            Post["/stop_all"] = _ =>
            {
                Task task = Task.Factory.StartNew(() =>
                {
                    Thread.CurrentThread.IsBackground = false;
                    Data.DbContext dbContext = Data.DbContext.CurrentContext;
                    List<Entity.SystemCronConfigData> list = dbContext.SystemCronConfigData.ToList();

                    list.ForEach(data =>
                    {
                        data.IsValidity = false;
                        dbContext.Entry(data).State = System.Data.Entity.EntityState.Modified;
                        ScheduledTask.ScheduledTaskManager.StopTask(data);
                    });
                    dbContext.SaveChanges();
                });
                return new Models.CommandResult();
            };

            Get["/info"] = _ =>
            {
                int jobid = int.Parse(Request.Query.id);
                Data.DbContext dbContext = Data.DbContext.CurrentContext;
                Entity.SystemCronConfigData data = dbContext.SystemCronConfigData.Where(x => x.JobId == jobid).FirstOrDefault();
                return Newtonsoft.Json.JsonConvert.SerializeObject(data);
            };

            Post["/save"] = _ =>
            {
                try
                {
                    int jobid = int.Parse(Request.Form.JobId.ToString());
                    DateTime next_time = DateTime.Parse(Request.Form.NextTime.ToString());
                    int timespan = int.Parse(Request.Form.TimeSpan.ToString());
                    int job_type = int.Parse(Request.Form.JobType.ToString());
                    string cron_expression = Request.Form.CronExpression.ToString();

                    Data.DbContext dbContext = Data.DbContext.CurrentContext;
                    Entity.SystemCronConfigData data = dbContext.SystemCronConfigData.Where(x => x.JobId == jobid).FirstOrDefault();
                    if (job_type == 9)
                    {
                        data.CronExpression = cron_expression;
                    }
                    else
                    {
                        data.NextTime = next_time;
                        data.TimeSpan = timespan;
                    }
                    data.JobType = job_type;

                    dbContext.Entry(data).State = System.Data.Entity.EntityState.Modified;
                    dbContext.SaveChanges();

                    ScheduledTask.ScheduledTaskManager.ExecuteTask(data);
                    return new Models.CommandResult();
                }
                catch (Exception ex)
                {
                    return new Models.CommandResult(ex.Message);
                }
            };
        }
    }
}